// index.js
// 获取应用实例
var publicApi = require('../../script/public.js');
var orderApi = require('../../script/order.js');
const app = getApp()
var config = require('../../script/config.js');

Page({
  data: {
    baseUrl: config.baseUrl,
    userinfo: null,
    msgList: [],
    totalMsg: 0,
    loading: false,
    noNotice: false,
    MenuList: [
      // {
      //   name: '待执行',
      //   icon: 'order_3.png',
      //   route: 'packageOrder/todoOrder/todoOrder',
      // },
      // {
      //   name: '待审核',
      //   icon: 'order_1.png',
      //   route: 'packageOrder/examineOrder/examineOrder',
      // },
      // {
      //   name: '待分派',
      //   icon: 'order_16.png',
      //   route: 'packageOrder/dispitchOrder/dispitchOrder',
      // },
      // {
      //   name: '待受理',
      //   icon: 'order_17.png',
      //   route: 'packageOrder/accept/accept',
      // },
      // {
      //   name: '工单池',
      //   icon: 'order_14.png',
      //   route: 'packageOrder/orderPow/orderPow',
      // },
      // {
      //   name: '二次派单',
      //   icon: 'order_2.png',
      //   url: 'packageOrder/reOrder/reOrder',
      // },
      // {
      //   name: '催办',
      //   icon: 'order_11.png',
      //   route: 'packageOrder/reminder/reminder',
      // },
      // {
      //   name: '报警统计',
      //   route: 'packageOrder/warn-statistic/warn-statistic',
      //   icon: 'icon_2.png'
      // }
    ],
    setMenu: [],
    favMenu: [],
    topMenu: [],
    myMenu: [],
    swiperHeight: 200
  },
  onLoad() {
    this.checkUpdate();
  },
  onShow() {
    this.getUserInfo();
    this.getStorageMenus();
    this.getTopMenu();
    this.getMyMenu();
    this.getWxOrderStatusCount();
    this.getMsgList();
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showNavigationBarLoading();
    this.getUserInfo();
    this.getMsgList();
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
  },
  checkUpdate() {
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      // console.log(res.hasUpdate)
    })
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '小程序版本更新，是否重启应用？',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    updateManager.onUpdateFailed(function () {
      // 新版本下载失败
    })
  },
  getUserInfo: function () {
    try {
      var value = wx.getStorageSync(config.storageKey.userinfo)
      if (value) {
        this.setData({
          userinfo: value
        });
        // if (this.data.userinfo.RoleTypeList) {
        //   const MenuList = [...this.data.MenuList];
        //   if (this.data.userinfo.RoleTypeList.indexOf('11') > -1) {
        //     const menu = MenuList.find(item => item.name === '待分派');
        //     menu.show = true;

        //     const menu1 = MenuList.find(item => item.name === '待审核');
        //     menu1.show = true;

        //     const menu2 = MenuList.find(item => item.name === '待受理');
        //     menu2.show = true;
        //   } else if (this.data.userinfo.RoleTypeList.indexOf('18') > -1) {
        //     const menu = MenuList.find(item => item.name === '待审核');
        //     menu.show = true;

        //     const menu1 = MenuList.find(item => item.name === '待受理');
        //     menu1.show = true;
        //   }
        //   const List = MenuList.filter(ite => ite.show);
        //   const ShowMenuList = [List.slice(0, 4), List.slice(4)];
        //   this.setData({
        //     MenuList,
        //     ShowMenuList
        //   });
        // }
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  getWxOrderStatusCount() {
    orderApi.GetWxOrderStatusCount().then(res => {
      if (res.code === 200) {
        const setMenu = [...this.data.setMenu];
        const favMenu = [...this.data.favMenu];
        for (let i = 0; i < setMenu.length; i++) {
          const setItem = setMenu[i]
          if (setItem.MENU_ID === 390101) { // 待执行
            setItem.Count = res.data.HandleCount;
          } else if (setItem.MENU_ID === 390106) { // 二次派单
            setItem.Count = res.data.ReOrderCount;
          } else if (setItem.MENU_ID === 390107) { // 催办
            setItem.Count = res.data.ReminderCount;
          } else if (setItem.MENU_ID === 390105) { // 工单池
            setItem.Count = res.data.OrderPoolCount;
          } else if (setItem.MENU_ID === 390103) { // 待分派
            setItem.Count = res.data.AssignCount;
          }
        }
        for (let i = 0; i < favMenu.length; i++) {
          const favItem = favMenu[i]
          if (favItem.MENU_ID === 390101) { // 待执行
            favItem.Count = res.data.HandleCount;
          } else if (favItem.MENU_ID === 390106) { // 二次派单
            favItem.Count = res.data.ReOrderCount;
          } else if (favItem.MENU_ID === 390107) { // 催办
            favItem.Count = res.data.ReminderCount;
          } else if (favItem.MENU_ID === 390105) { // 工单池
            favItem.Count = res.data.OrderPoolCount;
          } else if (favItem.MENU_ID === 390103) { // 待分派
            favItem.Count = res.data.AssignCount;
          }
        }
        this.getTopMenu();
        this.getMyMenu();
      }
    });
  },
  getStorageMenus() {
    const setMenu = wx.getStorageSync('setMenu');
    if (setMenu && setMenu != '') {
      this.setData({
        setMenu
      });
    }
    const favmenu = wx.getStorageSync('favmenu');
    if (favmenu && favmenu != '') {
      this.setData({
        favMenu: favmenu
      });
    }
  },
  getTopMenu() {
    let chunkedArrays = [];
    for (let i = 0; i < this.data.setMenu.length; i += 9) {
      chunkedArrays.push(this.data.setMenu.slice(i, i + 9));
    }
    if (chunkedArrays.length === 0) chunkedArrays = [
      []
    ];
    this.setData({
      topMenu: chunkedArrays,
      swiperHeight: chunkedArrays[0].length >= 5 ? 200 : 100
    });
  },
  getMyMenu() {
    const menus = [...this.data.favMenu];
    menus.sort((a, b) => {
      return b.VisitCount - a.VisitCount
    });
    const list = menus.slice(0, 5)
    this.setData({
      myMenu: list
    });
  },
  swiperChange(e) {
    const current = e.detail.current;
    const swiperItem = this.data.topMenu[current];
    let h = 0;
    if (swiperItem.length >= 5) {
      h = 200;
    } else {
      h = 100;
    }
    this.setData({
      swiperHeight: h
    });
  },
  toPage(e) {
    var menu = e.currentTarget.dataset.menu;
    this.setFavMenu(menu);
    wx.navigateTo({
      url: menu.PATH
    });
  },
  setFavMenu(menu) {
    wx.getStorage({
      key: 'favmenu',
      success(res) {
        const favmenu = res.data;
        const thisMenu = favmenu.find(m => m.MENU_ID === menu.MENU_ID);
        if (thisMenu) {
          thisMenu.VisitCount += 1;
        } else {
          favmenu.push({
            MENU_ID: menu.MENU_ID,
            PATH: menu.PATH,
            TITLE: menu.TITLE,
            ICON: menu.ICON,
            VisitCount: 1
          })
        }
        wx.setStorageSync('favmenu', favmenu);
      },
      fail(err) {
        const newMenu = {
          ...menu,
          VisitCount: 1
        }
        wx.setStorageSync('favmenu', [newMenu]);
      }
    })
  },
  toAppCenter() {
    wx.navigateTo({
      url: '/packageSys/app-center/app-center'
    });
  },
  getMsgList: function () {
    const params = {
      pagination: JSON.stringify({
        page: 1,
        rows: 2,
        sidx: 'sendTime',
        sord: 'desc'
      }),
      queryJson: JSON.stringify({
        msgType: "1,2",
        msgStatus: 0
      })
    };
    publicApi.GetMsgList(params).then(res => {
      if (res.code === 200) {
        // const multiple = res.data.Items.length > 1 ? 2 : 1;
        this.setData({
          msgList: res.data.Items,
          totalMsg: res.data.TotalCount,
          noNotice: res.data.TotalCount === 0
          // multiple: multiple
        })
      }
    })
  },
  noticeClick() {
    wx.navigateTo({
      url: "/packageSys/notice/notice"
    });
  },
  toNoticeDetail() {
    const notice = e.currentTarget.dataset.notice
    if (!notice.isNotice) return;
    const businessId = notice.businessId
    const msgStatus = notice.msgStatus
    if (businessId) {
      if (msgStatus === 0) {
        wx.navigateTo({
          url: "/packageSys/notice-detail/notice-detail?businessId=" + businessId + "&msgId=" + notice.msgId
        })
      } else {
        wx.navigateTo({
          url: "/packageSys/notice-detail/notice-detail?businessId=" + businessId
        })
      }
    }
  },
})